//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package docker_dao

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"atomgit.com/openlinksaas/proto-gen-go.git/docker_template_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type CateInfoDbItem struct {
	CateId   string `bson:"_id" json:"_id"`
	CateName string `bson:"cateName" json:"cateName"`
	AppCount uint32 `bson:"appCount" json:"appCount"`
}

func (item *CateInfoDbItem) ToCateInfo() *docker_template_api.CateInfo {
	return &docker_template_api.CateInfo{
		CateId:   item.CateId,
		CateName: item.CateName,
		AppCount: item.AppCount,
	}
}

type _CateDao struct {
	mc *mongo.Collection
}

func newCateDao(db *mongo.Database) (*_CateDao, error) {
	mc := db.Collection(db_ns.DB_NS_DOCKER + "cate")
	return &_CateDao{mc: mc}, nil
}

func (db *_CateDao) Insert(ctx context.Context, dbItem *CateInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_CateDao) List(ctx context.Context) ([]*CateInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{}, options.Find().SetSort(bson.M{"_id": 1}))
	if err != nil {
		return nil, err
	}
	retList := []*CateInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_CateDao) Exist(ctx context.Context, cateId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": cateId})
	return count > 0, err
}

func (db *_CateDao) Get(ctx context.Context, cateId string) (*CateInfoDbItem, error) {
	retItem := &CateInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": cateId}).Decode(retItem)
	return retItem, err
}

func (db *_CateDao) Remove(ctx context.Context, cateId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": cateId})
	return err
}

func (db *_CateDao) Update(ctx context.Context, cateId, cateName string) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": cateId}, bson.M{"$set": bson.M{"cateName": cateName}})
	return err
}

func (db *_CateDao) UpdateAppCount(ctx context.Context, cateId string, count uint32) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": cateId}, bson.M{"$set": bson.M{"appCount": count}})
	return err
}
